package com.yuantu.judiciary.aop;

import com.yuantu.judiciary.annotation.External;
import com.yuantu.judiciary.dao.IExternalRequestRecordDao;
import com.yuantu.judiciary.dao.ISearchRecordInfoDao;
import com.yuantu.judiciary.exception.enums.ExternalExceptionEnum;
import com.yuantu.judiciary.model.domain.ExternalQuestRecordDO;
import com.yuantu.judiciary.utils.AssertUtil;
import com.yuantu.judiciary.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Slf4j
@Aspect
@Component
public class ExternalAspect {

    @Autowired
    private IExternalRequestRecordDao externalRequestRecordDao;

    @Autowired
    private ISearchRecordInfoDao searchRecordInfoDao;

    @Before(value = "@annotation(controllerExternal)")
    private void doBefore(JoinPoint joinPoint, External controllerExternal) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String ticket = request.getHeader("ticket");
            AssertUtil.assertTrue(!StringUtil.isEmpty(ticket), ExternalExceptionEnum.TICKET_NOT_EXIST);
            ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
            AssertUtil.assertTrue(externalQuestRecord != null, ExternalExceptionEnum.TICKET_NOT_REGISTER);
            int requestNum = searchRecordInfoDao.countBySearchEncrypt(externalQuestRecord.getRequestKey());
            AssertUtil.assertTrue(externalQuestRecord.getRequestNum() > requestNum, ExternalExceptionEnum.REQUEST_NUM_NOT_ENOUGH);
        }
    }


}
